package com.gene.tlonpo.processor;

import java.text.MessageFormat;
import java.util.concurrent.atomic.AtomicInteger;

import com.gene.tlonpo.guard.Guard;
import com.gene.tlonpo.guard.interf.GuardI;
import com.gene.tlonpo.processor.inter.GuardIDecoraterI;
import com.gene.tlonpo.util.IPUtil;

/**
 * @author gene
 * 哨兵entity装饰器
 * @see com.gene.tlonpo.guard.Guard
 * 单例
 */
public class GuardDecorater implements GuardIDecoraterI {

    public static final GuardDecorater GUARD_DECORATER = new GuardDecorater();

    private final AtomicInteger subfix = new AtomicInteger();

    private static final String GUARD_ID_PARTTEN = "{0}-{1}";

    private GuardDecorater() {
    }

    /**
     * 装饰哨兵，完成哨兵的ip信息，和guardId的生成
     *
     * @param guardI guard interface
     */
    @Override
    public void decorate(final GuardI guardI) {
        if (!(guardI instanceof Guard)) {
            throw new RuntimeException(
                "can not execute guardDecorater,because of param type is not com.gene.tlonpo.guard.Guard");
        }
        Guard guard = (Guard)guardI;

        //localIp
        guard.setLocalIp(IPUtil.getLocalIp());
        //guardId
        guard.setGuardId(MessageFormat.format(GUARD_ID_PARTTEN, guard.getLocalIp(), subfix.incrementAndGet()));

    }
}
